<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta name="description" content="事务的实现机制与实际应用:   事务概述 事务控制语句 事务隔离级别 InnoDB锁机制">
<meta name="keywords" content="Android、iOS、Web、React Native">
<meta property="og:type" content="article">
<meta property="og:title" content="MySQL-基础---事务">
<meta property="og:url" content="http://yoursite.com/blog/2018/08/06/MySQL/MySQL-基础---事务/index.html">
<meta property="og:site_name" content="凌浩雨_博客">
<meta property="og:description" content="事务的实现机制与实际应用:   事务概述 事务控制语句 事务隔离级别 InnoDB锁机制">
<meta property="og:locale" content="default">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/3110861-db750d157a963e07.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:updated_time" content="2018-08-06T10:36:10.175Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="MySQL-基础---事务">
<meta name="twitter:description" content="事务的实现机制与实际应用:   事务概述 事务控制语句 事务隔离级别 InnoDB锁机制">
<meta name="twitter:image" content="http://upload-images.jianshu.io/upload_images/3110861-db750d157a963e07.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/blog/2018/08/06/MySQL/MySQL-基础---事务/"/>





  <title>MySQL-基础---事务 | 凌浩雨_博客</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="default">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">凌浩雨_博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            Archives
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/blog/blog/2018/08/06/MySQL/MySQL-基础---事务/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="凌浩雨">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.jpeg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="凌浩雨_博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">MySQL-基础---事务</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2018-08-06T18:01:39+08:00">
                2018-08-06
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>事务的实现机制与实际应用: </p>
<ul>
<li>事务概述</li>
<li>事务控制语句</li>
<li>事务隔离级别</li>
<li>InnoDB锁机制<a id="more"></a>
</li>
</ul>
<ol>
<li>事务概述<br>事务特性: </li>
</ol>
<ul>
<li>原子性(Atomicity): 事务中所有的操作视为一个原子单元，即对事务所进行的数据修改等操作只能是完全提交或者完全回滚。</li>
<li>一致性(Consistency):  事务在完成时，必须使所有的数据从一种一致性状态变更为另外一种一致性状态，所有的变更都必须应用于事务的修改，以确保数据的完整性。</li>
<li>隔离性(Isolation):一个事务中的操作语句所做的修改必须与其他事务所做的修改相隔离。在进行事务查看数据时，数据所处的状态，要么是被另一并发事务修改之前的状态，要么是被另一并发事务修改之后的状态，即当前事务不会查看由另一个并发事务正在修改的数据。这种特性通过锁机制实现。</li>
<li>持久性(Durability): 事务完成之后，所做的修改对数据的影响是永久的，即使系统重启或者出现系统故障数据仍可以恢复。</li>
</ul>
<p>(1) REDO日志<br>事务执行时需要将执行的事务日志写入到日志文件里，对应的文件为REDO日志。日志缓冲区的刷新方法或者时间间隔可以通过参数innodb_flush_log_at_trx_commit控制。<br>REDO日志对应磁盘上的ib_logfileN文件，该文件默认为5MB，建议设置为512MB以便容纳较大的事务。其中ib_logfile0和ib_logfile1为REDO日志。<br><img src="http://upload-images.jianshu.io/upload_images/3110861-db750d157a963e07.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="REDO日志路径.png"></p>
<p>(2) UNDO日志<br>与REDO日志相反，UNDO日志主要用于事务异常时的数据回滚，具体内容就是复制事务前的数据库内容到UNDO缓冲区，然后在合适的时间将内容刷新到磁盘。</p>
<ol start="2">
<li><p>事务控制语句</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line"> # 查看MySQL隔离级别</span><br><span class="line"> show variables like &apos;tx_isolation&apos;;</span><br><span class="line"># 创建测试需要的表，注意存储引擎为InnoDB</span><br><span class="line">use test</span><br><span class="line"># 创建表</span><br><span class="line">create table test_1(</span><br><span class="line">          id int,</span><br><span class="line">          username varchar(20)</span><br><span class="line">)engine=InnoDB;</span><br><span class="line"># 插入语句</span><br><span class="line"> insert into test_1</span><br><span class="line">          values(1,&apos;petter&apos;),</span><br><span class="line">          (2,&apos;bob&apos;),(3,&apos;allen&apos;),(4,&apos;aron&apos;);</span><br><span class="line"># 查询数据</span><br><span class="line">select * from test_1;</span><br><span class="line"></span><br><span class="line"> # 开启一个事务</span><br><span class="line"> begin;</span><br><span class="line"></span><br><span class="line"> # 更新一条记录</span><br><span class="line"> update test_1 set username=&apos;test&apos; where id=1;</span><br><span class="line">OK, 1 row affected (0.00 sec)</span><br><span class="line"></span><br><span class="line"> # 提交事务</span><br><span class="line"> commit;</span><br><span class="line"></span><br><span class="line"> # 查询数据</span><br><span class="line"> select * from test_1;</span><br><span class="line"></span><br><span class="line"> # 开启另一个事务</span><br><span class="line"> begin;</span><br><span class="line"># 更新数据</span><br><span class="line"> update test_1 set username=&apos;petter&apos; where id=1;</span><br><span class="line"># 查询数据</span><br><span class="line"> select*from test_1;</span><br><span class="line"> # 回滚事务</span><br><span class="line"> rollback;</span><br><span class="line"> # 查询数据</span><br><span class="line"> select * from test_1;</span><br></pre></td></tr></table></figure>
</li>
<li><p>事务隔离级别</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"># 未提交读</span><br><span class="line">set global transaction isolation level read uncommitted;</span><br><span class="line"># 提交读</span><br><span class="line">set global transaction isolation level read committed;</span><br><span class="line"># 可重复读</span><br><span class="line">set global transaction isolation level repeatable read;</span><br><span class="line"># 可串行读</span><br><span class="line">set global transaction isolation level serializable;</span><br></pre></td></tr></table></figure>
</li>
</ol>
<p>(1)READ-UNCOMMITTED(读取未提交内容)<br>在该隔离级别，所有事务都可以看到其他未提交事务的执行结果。读取未提交的数据被称为脏读(Dirty Read);<br>(2)READ-COMMITTED(读取提交内容)<br>这是大多数数据库系统的默认隔离级别，但不是MYSQL的默认隔离级别。满足了隔离的简单定义: 一个事务从开始到提交前所做的任何改变都是不可见的，事务只能看见已经提交事务所做的改变。这种隔离级别也支持所谓的不可重复读(Nonrepeatable Read)，因为同一事务的其他实例在该实例处理期间可能会有新的数据提交导致数据改变，所以同一查询可能返回不同结果，此级别导致不可重复读。<br>(3)REPEATABLE-READ(可重读)<br>这是MYSQL默认的事务隔离级别，能确保同一事务的多个实例在并发读取数据时，会看到同样的数据行。理论上会导致幻读(Phantom Read)。<br>(4) Serializable(可串行化)<br>这是最高的隔离级别，通过强制事务排序，是之不可能相互冲突，从而解决幻读问题。简言之，就是在每个读的数据行上加上共享锁实现。这个级别，可能会导致大量的超时现象和所竞争，一般不推荐使用。</p>
<ol start="4">
<li>InnoDB锁机制<br>(1) 锁的类型(共享锁/排他锁/意向锁)</li>
</ol>
<ul>
<li>共享锁<br>共享锁代号是S，是Share的缩写，共享锁的所力度是行或者元组(多个行)。一个事务获取了共享锁之后，可以对锁定范围内的数据执行读操作。</li>
<li>排他锁<br>排他锁的代号是X，是eXclusive的缩写，排他锁的粒度与共享锁相同，也是行或者元组。一个事务获取了排他锁之后，可以对锁定范围内的数据执行写操作。</li>
<li>意向锁<br>意向锁是一种表锁，锁定的粒度是整张表，分为意向共享锁(IS)和意向排他锁(IX)两类。意向共享锁表示一个事务有意对数据上共享锁或者排他锁。“有意”表示事务想执行操作但还没有真正执行。<br>(2) 锁粒度<br>锁的粒度主要分为表锁和行锁。<br>表锁管理锁的开销最小，同时允许的并发量也是最小的锁机制。行锁可以支持最大的并发。</li>
</ul>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2018/08/06/Maven/Maven入门/" rel="next" title="Maven入门">
                <i class="fa fa-chevron-left"></i> Maven入门
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2018/08/06/MySQL/MySQL-基础---单表数据记录查询/" rel="prev" title="MySQL-基础---单表数据记录查询">
                MySQL-基础---单表数据记录查询 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/blog/images/avatar.jpeg"
                alt="凌浩雨" />
            
              <p class="site-author-name" itemprop="name">凌浩雨</p>
              <p class="site-description motion-element" itemprop="description">专业从事于移动端开发，Android与iOS均有涉及，主做Android开发与React Native开发</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">393</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            

            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">凌浩雨</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
